<?php

namespace Common\Model;

use Think\Model;

/**
 * 社区帖子分类模型
 * Class BbsClassModel
 * @package Common\Model
 */
class BbsClassModel extends Model
{

    const NORMAL = 0;           // 状态：正常
    const DELTEL = -1;          // 状态：卸任状态

    const BBS_CLASS_KEY = 'bbsclass:';  // 社区分类缓存

    private static $default = [0 => '默认'];  // 默认分类

    /**
     * 添加分类记录
     * @param $bid
     * @param $name
     * @return mixed
     */
    public static function addData($bid, $name)
    {
        $data = [
            'bid' => $bid,
            'name' => $name
        ];
        if ($cid = M('BbsClass')->add($data)) {
            self::clearCache($bid);
        }
        return $cid;
    }

    /**
     * 获取社区分类
     * @param $bid
     * @return array|mixed
     */
    public static function getClassById($bid)
    {
        $key = self::BBS_CLASS_KEY.$bid;
        $result = S($key);
        if(false !== $result){
            return $result;
        }
        $result = M('BbsClass')->where(['bid' => $bid, 'status' => self::NORMAL])->field('id,name')->order('sort desc')->select();
        if (false !== $result) {
            foreach ($result as $value) {
                self::$default[$value['id']] = $value['name'];
            }
            S($key, self::$default);
        }
        return self::$default;
    }

    public static function clearCache($bid){
        $key = self::BBS_CLASS_KEY.$bid;
        S($key, null);
    }

}